// File: jmcomic-core/src/main/java/dev/jukomu/jmcomic/entity/JmImageDetail.java
package dev.jukomu.jmcomic.entity;

import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.Objects;

/**
 * 对应Python的JmImageDetail，表示禁漫的图片详情。
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class JmImageDetail extends JmBaseEntity implements Downloadable {

    private String aid; // 本子ID或章节ID（如果单章节）
    private String scrambleId; // 图片所属章节的解密ID
    private String imgUrl; // 图片的原始URL，不含查询参数
    private String imgFileName; // 图片文件名（不含后缀）
    private String imgFileSuffix; // 图片后缀（含点）

    private JmPhotoDetail fromPhoto; // 图片所属章节的引用
    private String queryParams; // 图片URL的查询参数，例如 ?v=时间戳
    private int index; // 图片在章节中的索引，从1开始

    // Downloadable接口的字段
    private String savePath;
    private boolean exists;
    private boolean skip;

    /**
     * 构造函数。
     *
     * @param aid           本子ID或章节ID
     * @param scrambleId    图片所属章节的解密ID
     * @param imgUrl        图片的原始URL
     * @param imgFileName   图片文件名（不含后缀）
     * @param imgFileSuffix 图片后缀（含点）
     * @param fromPhoto     图片所属章节的引用
     * @param queryParams   图片URL的查询参数
     * @param index         图片在章节中的索引（从1开始）
     */
    public JmImageDetail(String aid, String scrambleId, String imgUrl, String imgFileName, String imgFileSuffix, JmPhotoDetail fromPhoto, String queryParams, int index) {
        Objects.requireNonNull(scrambleId, "scrambleId cannot be null for JmImageDetail");
        this.aid = aid;
        this.scrambleId = scrambleId;
        this.imgUrl = imgUrl;
        this.imgFileName = imgFileName;
        this.imgFileSuffix = imgFileSuffix;
        this.fromPhoto = fromPhoto;
        this.queryParams = queryParams;
        this.index = index;
    }

    /**
     * 静态工厂方法，用于创建JmImageDetail实例。
     * 对应Python的of方法。
     *
     * @param photoId      章节ID
     * @param scrambleId   解密ID
     * @param dataOriginal 图片的原始URL（可能含查询参数）
     * @param fromPhoto    图片所属章节的引用
     * @param queryParams  图片URL的查询参数
     * @param index        图片在章节中的索引
     * @return JmImageDetail实例
     */
    public static JmImageDetail of(String photoId, String scrambleId, String dataOriginal, JmPhotoDetail fromPhoto, String queryParams, int index) {
        int lastSlashIndex = dataOriginal.lastIndexOf('/');
        int lastDotIndex = dataOriginal.lastIndexOf('.');
        String fileNameWithoutSuffix;
        String fileSuffix;

        if (lastSlashIndex != -1 && lastDotIndex != -1 && lastDotIndex > lastSlashIndex) {
            fileNameWithoutSuffix = dataOriginal.substring(lastSlashIndex + 1, lastDotIndex);
            fileSuffix = dataOriginal.substring(lastDotIndex);
        } else {
            // Fallback if URL format is unexpected
            fileNameWithoutSuffix = dataOriginal.substring(lastSlashIndex + 1);
            fileSuffix = ""; // No suffix found
        }

        return new JmImageDetail(
                photoId,
                scrambleId,
                dataOriginal, // imgUrl should be the base URL without query params
                fileNameWithoutSuffix,
                fileSuffix,
                fromPhoto,
                queryParams,
                index
        );
    }

    /**
     * 获取不包含后缀的文件名。
     *
     * @return 文件名字符串
     */
    public String getFilenameWithoutSuffix() {
        return imgFileName;
    }

    /**
     * 获取完整的文件名（包含后缀）。
     *
     * @return 文件名字符串
     */
    public String getFilename() {
        return imgFileName + imgFileSuffix;
    }

    /**
     * 判断图片是否为GIF格式。
     *
     * @return 如果是GIF返回 true
     */
    public boolean isGif() {
        return ".gif".equalsIgnoreCase(imgFileSuffix);
    }

    /**
     * 获取图片的下载URL（包含查询参数）。
     *
     * @return 下载URL字符串
     */
    public String getDownloadUrl() {
        if (queryParams == null || queryParams.isEmpty()) {
            return imgUrl;
        }
        return imgUrl + "?" + queryParams;
    }

    /**
     * 获取图片的标签，用于日志打印等。
     * 格式："AID/文件名 [索引/总数]"
     *
     * @return 图片标签字符串
     */
    public String getTag() {
        String albumOrPhotoId = (fromPhoto != null && fromPhoto.getAlbumId() != null) ? fromPhoto.getAlbumId() : aid;
        String totalPages = (fromPhoto != null) ? String.valueOf(fromPhoto.size()) : "?";
        return String.format("%s/%s%s [%d/%s]", albumOrPhotoId, imgFileName, imgFileSuffix, index, totalPages);
    }

    @Override
    public boolean isImage() {
        return true;
    }

    @Override
    public String toString() {
        return String.format("JmImageDetail(image-[%s])", getDownloadUrl());
    }

    // --- Getters for fields ---
    public String getAid() {
        return aid;
    }

    public String getScrambleId() {
        return scrambleId;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public String getImgFileName() {
        return imgFileName;
    }

    public String getImgFileSuffix() {
        return imgFileSuffix;
    }

    public JmPhotoDetail getFromPhoto() {
        return fromPhoto;
    }

    public String getQueryParams() {
        return queryParams;
    }

    public int getIndex() {
        return index;
    }

    // --- Setters for Downloadable interface ---
    @Override
    public String getSavePath() {
        return savePath;
    }

    @Override
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    @Override
    public boolean isExists() {
        return exists;
    }

    @Override
    public void setExists(boolean exists) {
        this.exists = exists;
    }

    @Override
    public boolean isSkip() {
        return skip;
    }

    @Override
    public void setSkip(boolean skip) {
        this.skip = skip;
    }

    // --- Setters for other properties if needed for external modification ---
    public void setAid(String aid) {
        this.aid = aid;
    }

    public void setScrambleId(String scrambleId) {
        this.scrambleId = scrambleId;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public void setImgFileName(String imgFileName) {
        this.imgFileName = imgFileName;
    }

    public void setImgFileSuffix(String imgFileSuffix) {
        this.imgFileSuffix = imgFileSuffix;
    }

    public void setFromPhoto(JmPhotoDetail fromPhoto) {
        this.fromPhoto = fromPhoto;
    }

    public void setQueryParams(String queryParams) {
        this.queryParams = queryParams;
    }

    public void setIndex(int index) {
        this.index = index;
    }
}